from rest_framework import serializers
from . import models
from django.conf import settings
from custom.models import CustomUp, CustomProject


class ProjectModelSerializer(serializers.ModelSerializer):
    """
    ymq
    产品序列化
    """

    class Meta:
        model = models.Project
        fields = ['id', 'title', 'home_img', 'watch_num', 'comment_num', 'style']


class ProjectDetailModelSerializer(serializers.ModelSerializer):
    """
    ymq
    产品详细序列化
    """
    goods_info = serializers.SerializerMethodField()
    goods_img = serializers.SerializerMethodField()
    pjDataList = serializers.SerializerMethodField()
    is_shoucang = serializers.SerializerMethodField()
    num = serializers.SerializerMethodField()

    class Meta:
        model = models.Project
        fields = ['id', 'goods_info', 'goods_img', 'pjDataList', 'is_shoucang', 'num']

    def get_goods_info(self, obj):
        """
        商品详细
        """
        goods_info = {'goods_id': obj.id, 'goods_title': obj.title, 'goods_price': obj.price,
                      'goods_time': obj.renovation_time, 'goods_diqu': obj.renovation_range,
                      'goods_xiaoliang': obj.sales_volume, 'content': obj.desc}
        return goods_info

    def get_goods_img(self, obj):
        """
        商品轮播图
        """
        """
        goods_img: [
         {'img': 'https://tgi12.jia.com/129/144/29144025.jpg'},
         {'img': 'https://tgi1.jia.com/129/144/29144031.jpg' },
         {'img': 'https://tgi1.jia.com/129/144/29144032.jpg' },
         {'img': 'https://tgi13.jia.com/127/342/27342599.jpg' },
         ]
        """
        pro_img_list = obj.p_p.all()

        return [{'id': item.id, 'img': settings.NEW_BASE_URL + item.image.url} for item in pro_img_list]

    def get_pjDataList(self, obj):
        """
        获取评论
        """
        """
        
        [
     { headpic: 'https://tgi13.jia.com/127/342/27342599.jpg', author: '张三', add_time: '2018-06-01', content:'好评好评，真实太好了!'},
     { headpic: 'https://tgi13.jia.com/127/342/27342599.jpg', author: '张三', add_time: '2018-06-01', content: '好评好评，真实太好了!' }
   ]
        """
        pro_img_list = obj.pc_p.all().filter(depth=1, reply__isnull=True)[:2]
        good_list = [{'headpic': item.userinfo.icon, 'author': item.userinfo.username,
                      'add_time': str(item.create_time).replace('T', ' '),
                      'content': item.comment} for item in pro_img_list]
        # 如果评论为空
        if not good_list:
            good_list = [{'headpic': '', 'author': '', 'add_time': '',
                          'content': '暂无评价！'}]
        return good_list

    def get_is_shoucang(self, obj):
        # print(obj.id)
        user = self.context['request'].user
        return models.Shoucang.objects.filter(userinfo_id=user.id, project_id=obj.id).exists()

    def get_num(self, obj):
        user = self.context['request'].user
        # 观看人数加一
        obj.watch_num += 1
        obj.save()
        # print(obj.watch_num, '>>>>>>>>>>>>')
        return obj.watch_num


class ShoucangUpvoteModelSerializer(serializers.ModelSerializer):
    id = serializers.CharField()

    # is_shoucang = ShoucangModelSerializer()    # read_only=True
    # is_shoucang = serializers.CharField()

    class Meta:
        model = models.Project  # {"id":4,"is_shoucang":"True"}
        fields = ['id']  # 产品id

    def _chock_id(self, id):  # 验证商品是否存在
        project_obj = models.Project.objects.get(id=id)


class ProjectShoucangModelSerializer(ShoucangUpvoteModelSerializer):


    def validate(self, attrs):
        # 判断id是否存在，
        id = attrs.get('id')
        # is_shoucang = attrs.get('is_shoucang')
        # print(is_shoucang)
        self._chock_id(id)
        # 创建收藏表 is_shoucang字段
        request = self.context.get('request')
        user = request.user
        #先去数据库中查询
        shoucang_obj = models.Shoucang.objects.filter(project_id=id, userinfo_id=user.id).first()

        # print(shoucang_obj.shoucang_project.is_shoucang)
        if not shoucang_obj:
            shoucang_obj1 = models.Shoucang.objects.create(project_id=id, userinfo_id=user.id, is_shoucang=True)
            self.context['is_shoucang'] = shoucang_obj1.is_shoucang
        else:
            shoucang_obj.is_shoucang = not shoucang_obj.is_shoucang
            shoucang_obj.save()
            self.context['is_shoucang'] = shoucang_obj.is_shoucang
        return attrs


class ProjectUpvoteModelSerializer(ShoucangUpvoteModelSerializer):
    def _chock_customproject_id(self, id):  # 验证商品是否存在
        project_obj = CustomProject.objects.get(id=id)
    """
    点赞序列化
    """
    def validate(self, attrs):
        # 判断id是否存在，
        id = attrs.get('id')
        # is_shoucang = attrs.get('is_shoucang')
        # print(is_shoucang)

        # 创建收藏表 is_shoucang字段
        request = self.context.get('request')
        type = request.data.get('type')

        user = request.user
        if type == 'indexdetail':
            self._chock_id(id)
            ProjectUp_obj = models.ProjectUp.objects.filter(project_id=id, userinfo_id=user.id).first()

            if not ProjectUp_obj:  # 没有点赞，创建表
                ProjectUp_obj1 = models.ProjectUp.objects.create(project_id=id, userinfo_id=user.id, is_upvote=True)
                self.context['is_upvote'] = True
            else:
                self.context['is_upvote'] = False
        else:
            self._chock_customproject_id(id)
            customup_obj = CustomUp.objects.filter(custom_id=id, userinfo_id=user.id).first()

            if not customup_obj:  # 没有点赞，创建表

                customup_obj1 = CustomUp.objects.create(custom_id=id, userinfo_id=user.id)
                customup_obj1.custom.comment_up += 1
                customup_obj1.custom.save()
                self.context['is_upvote'] = True
            else:

                self.context['is_upvote'] = False
        return attrs


class ProjectDetailContentModelSerializer(serializers.ModelSerializer):
    """
    产品页面序列化器
    """

    class Meta:
        model = models.Project

        fields = ['id', 'desc', 'product_parameters', 'after_sales', 'home_img', 'price', 'title']


class MyLoveModelSerializer(serializers.ModelSerializer):
    """
    我的收藏
    """
    content = serializers.SerializerMethodField()
    name = serializers.SerializerMethodField()
    img = serializers.SerializerMethodField()
    id = serializers.SerializerMethodField()

    class Meta:
        model = models.Shoucang
        fields = ['id', 'content', 'name', 'img']

    def get_id(self, obj):
        return obj.project.id

    def get_content(self, obj):
        return obj.project.title

    def get_name(self, obj):
        return obj.userinfo.username

    def get_img(self, obj):
        img = settings.NEW_BASE_URL + obj.project.home_img.url
        # print(img)
        return img
